package com.yun.apply.system.service.impl;

import com.yun.apply.system.domain.SysRoleMenu;
import com.yun.apply.system.mapper.SysRoleMapper;
import com.yun.apply.system.mapper.SysRoleMenuMapper;
import com.yun.apply.system.mapper.SysUserRoleMapper;
import com.yun.apply.system.service.ISysRoleService;
import com.yun.common.core.domain.SysRole;
import com.yun.common.exception.CustomException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class SysRoleServiceImpl implements ISysRoleService {

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysRoleMenuMapper roleMenuMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    /**
     * 根据用户ID查询权限
     *
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectRolePermissionByUserId(Long userId) {
        List<SysRole> perms = roleMapper.selectRolePermissionByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (SysRole perm : perms)
        {
            if (perm != null)
            {
                permsSet.addAll(Arrays.asList(perm.getRoleKey().trim().split(",")));
            }
        }
        return permsSet;
    }

    /**
     * 查询所有角色
     *
     * @return 角色列表
     */
    @Override
    public List<SysRole> selectRoleAll() {
            return roleMapper.selectRoleList(null);
    }

    /**
     * 根据用户ID获取角色选择框列表
     *
     * @param userId 用户ID
     * @return 选中角色ID列表
     */
    @Override
    public List<Integer> selectRoleListByUserId(Long userId) {
        return roleMapper.selectRoleListByUserId(userId);
    }

    /**
     * 根据条件分页查询角色数据
     *
     * @param role 角色信息
     * @return 角色数据集合信息
     */
    @Override
    public List<SysRole> selectRoleList(SysRole role) {
        return roleMapper.selectRoleList(role);
    }

    /**
     * 新增保存角色信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Transactional
    @Override
    public int insertRole(SysRole role) {
        this.checkRole(role, "新增角色");
        role.setCreateTime(new Date());
        roleMapper.insert(role);
        return insertRoleMenu(role);
    }

    /**
     * 新增角色菜单信息
     *
     * @param role 角色对象
     */
    private int insertRoleMenu(SysRole role) {
        int rows = 1;
        // 新增用户与角色管理
        List<SysRoleMenu> list = new ArrayList<SysRoleMenu>();
        for (Long menuId : role.getMenuIds())
        {
            SysRoleMenu rm = new SysRoleMenu();
            rm.setRoleId(role.getRoleId());
            rm.setMenuId(menuId);
            list.add(rm);
        }
        if (list.size() > 0)
        {
            rows = roleMenuMapper.batchRoleMenu(list);
        }
        return rows;
    }

    /**
     * 修改保存角色信息
     *
     * @param role 角色信息
     * @return 结果
     */
    @Transactional
    @Override
    public int updateRole(SysRole role) {
        this.checkRole(role, "修改角色");
        // 修改角色信息
        roleMapper.updateById(role);
        // 删除角色与菜单关联
        roleMenuMapper.deleteRoleMenuByRoleId(role.getRoleId());
        role.setUpdateTime(new Date());
        return insertRoleMenu(role);
    }

    @Override
    public SysRole selectRoleById(Long roleId) {
        return roleMapper.selectById(roleId);
    }

    @Transactional
    @Override
    public int updateRoleStatus(SysRole role) {
        this.checkRoleAllowed(role);
        SysRole exitRole = roleMapper.selectById(role.getRoleId());
        if (exitRole == null) {
            throw new CustomException("角色不存在");
        }
        exitRole.setEnable(role.getEnable());
        return roleMapper.updateById(exitRole);
    }

    @Transactional
    @Override
    public int deleteRoleByIds(Long[] roleIds) {
        for (Long roleId : roleIds)
        {
            checkRoleAllowed(new SysRole(roleId));
            SysRole role = selectRoleById(roleId);
            if (userRoleMapper.countUserRoleByRoleId(roleId) > 0)
            {
                throw new CustomException(String.format("%1$s已分配,不能删除", role.getRoleName()));
            }
        }
        return roleMapper.deleteRoleByIds(roleIds);
    }


    /**
     * 校验角色是否允许操作
     *
     * @param role 角色信息
     */
    private void checkRoleAllowed(SysRole role)
    {
        if (role.getRoleId() != null && role.isAdmin())
        {
            throw new CustomException("不允许操作超级管理员角色");
        }
    }


    /**
     * 检查角色
     * @param role
     */
    private void checkRole(SysRole role, String mes) {
        Long roleId = role.getRoleId() == null ? -1L : role.getRoleId();
        int count = roleMapper.checkRoleNameUnique(role.getRoleName(), roleId);
        if (count > 0) {
            throw new CustomException(mes + "'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        count = roleMapper.checkRoleKeyUnique(role.getRoleKey(), roleId);
        if (count > 0) {
            throw new CustomException(mes + "'" + role.getRoleName() + "'失败，角色权限已存在");
        }
    }
}
